package com.xiao.xin.core.job;

import com.xiao.xin.comfyui.client.api.ComfyuiApi;
import com.xiao.xin.core.common.Constants;
import com.xiao.xin.core.domain.ComfyuiTask;
import com.xiao.xin.core.service.RedisService;
import com.xiao.xin.core.service.UserFundRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.HashMap;

@RequiredArgsConstructor
@Slf4j
@Component
public class RunTaskJob {

    private static final String SPRING_TASK_LOCK_KEY = "SPRING_TASK_LOCK_KEY";
    private final RedisService redisService;
    private final RedissonClient redissonClient;
    private final ComfyuiApi comfyuiApi;
    private final UserFundRecordService userFundRecordService;


    /***
     * SpringTask 定时任务
     */
    @Scheduled(cron = "*/1 * * * * *")
    public void task() {
        RLock lock = redissonClient.getLock(SPRING_TASK_LOCK_KEY);
        try {
            if (lock.tryLock()) {
                RSemaphore semaphore = redissonClient.getSemaphore(Constants.TASK_RUN_SEMAPHORE); // 获取一个信号值
                // 判断当前ZSet集合中是否有值
                if (redisService.hasQueueTask()) {
                    if (semaphore.tryAcquire()) {
                        sendComfyUI();
                    }
                }
            }
        } finally {
            lock.unlock();
        }
    }


    /***
     * 向Redis队列中添加数据
     */
    private void sendComfyUI() {

        // 获取一个数据 默认从头开始获取
        ComfyuiTask comfyuiTask = redisService.popQueueTask();


        if (comfyuiTask != null) {
            // ComfyUI添加任务
            Call<HashMap> hashMapCall = comfyuiApi.addQueueTask(comfyuiTask.getComfyuiRequestDto());
            try {
                // ComfyUI添加任务发起请求
                Response<HashMap> execute = hashMapCall.execute();
                if (execute.isSuccessful()) {
                    HashMap body = execute.body();
                    String promptId = body.get("prompt_id").toString();
                    comfyuiTask.setPromptId(promptId);
                    redisService.addStartedTask(comfyuiTask.getPromptId(), comfyuiTask);
                } else {
                    // 释放信号量
                    log.info("请求失败，释放信号量");
                    RSemaphore semaphore = redissonClient.getSemaphore(Constants.TASK_RUN_SEMAPHORE);
                    semaphore.release();
                    userFundRecordService.freezeReturn(comfyuiTask.getUserId(), comfyuiTask.getSize());
                }
            } catch (IOException e) {
                throw new RuntimeException("sendComfyUI出错");
            }
        }
    }


}
